<template>
  <div class="myContainer">
    <!-- 头部标题 start -->  
    <el-row class="myHeadeTitle">
      <el-col :span="24" class="myPadding_20px">
        <img src="static/images/wbStep1.png" alt="" title="" />
      </el-col>
    </el-row>
    <!-- 头部标题 end -->
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        所属小区 :
      </el-col>
      <el-col :span="8">
        <template>
          <el-cascader
            placeholder="全部项目/小区"
            :options="regionOptions"
            v-model="regionOptSelected"
            ></el-cascader>
          </el-select>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        所属计划模板 :
      </el-col>
      <el-col :span="8">
        <template>
          <el-select v-model="modelValue" @change="changeModel()" placeholder="所属计划模板">
            <el-option
              v-for="(item,index) in modelOptions"
              :key="item.id"
              :label="item.name"
              :value="index">
            </el-option>
          </el-select>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        模板说明 :
      </el-col>
      <el-col :span="8">
        <el-input type="textarea" placeholder="模板说明" v-model="note" disabled></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划对象 :
      </el-col>
      <el-col :span="8">
        <template>
          <el-select v-model="maintenanceValue" @change="getLastTime" placeholder="请选择计划对象">
            <el-option
              v-for="(item,index) in maintenanceOptions"
              :key="item.id"
              :label="item.targetname"
              :value="item.id+'-'+index">
            </el-option>
          </el-select>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        上次任务结束时间 :
      </el-col>
      <el-col :span="8">
        <el-input
          v-model="lastTimeValue"
          disabled
          placeholder="上次任务结束时间">
        </el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划周期 :
      </el-col>
      <el-col :span="8">
        <template>
          <el-select v-model="cycleValue" placeholder="请选择周期">
            <el-option
              v-for="item in cycleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划名称 :
      </el-col>
      <el-col :span="8">
        <el-input placeholder="计划名称" v-model="planName"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划负责人 :
      </el-col>
      <el-col :span="8">
        <el-input placeholder="计划负责人" v-model="dutyName" :data-id="dutyId" @focus="onPersonInCharge"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划检查人 :
      </el-col>
      <el-col :span="8">
        <el-input placeholder="计划检查人" v-model="examinerName" @focus="onExaminer"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划状态 :
      </el-col>
      <el-col :span="4" class="myLineHeight_45px">
        <template>
          <el-radio-group v-model="radio">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="15" :offset="3">
        <el-button type="primary" class="myBgGreen" @click="onNextStep">下一步</el-button>
      </el-col>
    </el-row>



    <!--选择负责人弹出框 start-->
    <el-dialog title="选择负责人" class="myRoleDialog" :visible.sync="newPersonnelDialogVisible">
      <el-row :gutter="10">
        <el-col :span="20">
          <el-input placeholder="输入关键词" v-model="kw_Personnel"></el-input>
        </el-col>
        <el-col :span="4" class="myTextAlignRight">
          <el-button type="primary" class="myBgGreen" @click="onSearch">查询</el-button>
        </el-col>
      </el-row>
      <div class="myPaddingTop_10px">
        <el-tree
          key="dutyDlg"
          class="myOV_y_400px" 
          ref="dutyDlg"
          v-loading="dutyDlgListLoading"
          :data="dutyDlgList"
          :props="dutyDlgProps"
          node-key="staff_id"
          @check-change="onChange"
          :render-content="renderContent"
          :filter-node-method="filterNode"
          show-checkbox>
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="myBgGreen" @click="newPersonnelDialogVisible = false">取 消</el-button>
        <el-button type="primary" class="myBgGreen" @click="handleDutyDlgClick">提 交</el-button>
      </div>
    </el-dialog>
    <!--选择负责人弹出框 end-->

    <!--选择检查人弹出框 start-->
    <el-dialog title="选择检查人" class="myRoleDialog" :visible.sync="newExaminerDialogVisible">
      <el-row :gutter="10">
        <el-col :span="20">
          <el-input placeholder="输入关键词" v-model="kw"></el-input>
        </el-col>
        <el-col :span="4" class="myTextAlignRight">
          <el-button type="primary" class="myBgGreen" @click="onSearchExaminer">查询</el-button>
        </el-col>
      </el-row>
      <div class="myPaddingTop_10px">
        <el-tree
          key="examinerDlg"
          class="myOV_y_400px" 
          ref="examinerDlg"
          v-loading="dutyDlgListLoading"
          :data="examinerDlgList"
          :props="dutyDlgProps"
          node-key="staff_id"
          @check-change="onChangeexaminerDlg"
          :render-content="renderContent"
          :filter-node-method="filterNodeExaminer"
          show-checkbox>
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="myBgGreen" @click="newExaminerDialogVisible = false">取 消</el-button>
        <el-button type="primary" class="myBgGreen" @click="onExaminerSub">提 交</el-button>
      </div>
    </el-dialog>
    <!--选择检查人弹出框 end-->
  </div>
</template>

<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myHeadeTitle{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid #dbdbdb;
    margin-bottom:10px; 
  }
  .myHeadeTitle:before,.myHeadeTitle:after{
    content: " ";
    display: block;
    clear: both;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top: 2px;
  }
  .myLineHeight_35px{
    line-height: 35px;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myPaddingTop_10px{
    padding-top: 10px;
  }  
  .myLeftMsg{
    line-height: 40px;
    text-align: right;
    padding-right: 10px;
  }
  .myPaddingBottom_10px{
    padding-bottom: 10px;
  }
  .myVA_M{
    vertical-align: middle;
  }
  .myPadding_20px{
    padding: 20px;
  }
  .myDialogSearchText{
    width: 360px;
  }
  .myLineHeight_45px{
    line-height: 45px;    
  }
  .myOV_y_400px{
    overflow-y: scroll;
    max-height: 400px;
    border:1px solid #f2f2f2;
  }
</style>
<script>
  import { extractAreaIds , onSetArea } from '@/utils/misc';
  import { getRegion } from '@/utils/localstorage';
  import { getModelManageList , getObjList } from '@/api/maintenanceplan';
  import { getStaffList } from '@/api/staff';
  export default {
    data(){
      return{
        modelValue:"",
        modelOptions:[],
        maintenanceValue:"",
        maintenanceOptions:[],
        lastTimeValue:"",
        planningCycleValue:"",
        planningCycleOptions:[{value: '选项1',label: '周期1'}, {value: '选项2',label: '周期2'}],
        newPersonnelDialogVisible:false,
        on:"",
        searchKW:"",
        regionOptions: [],
        regionOptSelected: [],
        note:"",
        cycleValue:"",
        cycleOptions:[],
        radio:1,
        dutyDlgListLoading:false,
        dutyDlgProps: {
          children: 'children',
          label: 'user_name'
        },
        dutyDlgList: [],
        dutyId:null,
        dutyName:"",//责任人
        newExaminerDialogVisible:false,
        examinerDlgList:[],
        examinerName:"",//检查人
        examinerId:"",
        planName:"",
        kw:"",
        type:"",
        areaList:[],
        kw_Personnel:""
      }
    },
    components: {
        
    },
    watch: {
      kw(val) {
        try{
          this.$refs.examinerDlg.filter(val);
        }catch(error){
          return;
        }
      },
      kw_Personnel(val){
        try{
          this.$refs.dutyDlg.filter(val);
        }catch(error){
          return;
        }
      },
      areaIds(val){
        try{
          this.dutyId=null;
          this.dutyName="";
          this.examinerName="";
          this.examinerId="";
        }catch(error){
          return;
        }
      }
    },
    computed: {
      areaIds() {
        return extractAreaIds(this.regionOptSelected, this.regionOptions);
      }
    },
    mounted(){
      let vm=this;
      document.title = '模板任务计划管理';
      vm.regionOptions = getRegion();
      this.regionOptSelected.push(this.regionOptions[0].value,this.regionOptions[0].children[0].value,this.regionOptions[0].children[0].children[0].value);
      vm.type = vm.$route.query.type;
      if(vm.type=="back"){
        let fsd=window.localStorage.getItem("firstStepData"); 
        let jsonFsd=JSON.parse(fsd);  
        vm.regionOptSelected=onSetArea(vm.regionOptions,jsonFsd.areaid);//读取缓存小区id     
        vm.modelOptions=JSON.parse(window.localStorage.back_modelOptions);//读取缓存计划模板列表
        vm.modelValue=parseInt(window.localStorage.back_modelValue);//读取缓存选中的维保计划模板下标-----
        vm.maintenanceOptions=JSON.parse(window.localStorage.back_maintenanceOptions);//读取缓存计划对象列表-----
        vm.maintenanceValue=window.localStorage.back_maintenanceValue;//读取缓存计划对象
        vm.lastTimeValue=window.localStorage.back_lastTimeValue;//读取缓存上次任务结束时间-----
        vm.cycleOptions=JSON.parse(window.localStorage.back_cycleOptions);//读取缓存周期列表---
        vm.planName=jsonFsd.planname;//读取缓存计划名称
        vm.cycleValue=jsonFsd.plan_peroid;//读取缓存周期
        
        vm.dutyName=window.localStorage.back_dutyName;//读取缓存责任人名
        vm.dutyId=jsonFsd.charge_userid;//读取缓存责任人id
        
        vm.examinerName=window.localStorage.back_examinerName;//读取缓存检查人名
        vm.examinerId=window.localStorage.back_examinerId;//读取缓存检查人id

        vm.radio=jsonFsd.valid;
        
      }else{
        vm.onGetModelManageList();
      }
    },
    methods:{
      filterNode(value, data) {
        if (!value) return true;
        return data.user_name.indexOf(value) !== -1;
      },
      filterNodeExaminer(value, data){
        if (!value) return true;
        return data.user_name.indexOf(value) !== -1;
      },     
      onNextStep:function(){
        let vm=this;
        if(!vm.planName || !vm.areaIds || !vm.modelOptions[vm.modelValue].id || !vm.dutyId || !vm.examinerId || !vm.maintenanceValue.split("-")[0] || !vm.cycleValue){
          vm.$message.error("数据填写完整才能进入下一步！")
          return;
        }

        let firstStepData={
          "planname":vm.planName,   //计划名称
          "areaid":vm.areaIds,   //小区id
          "template_id": vm.modelOptions[vm.modelValue].id,   //模板id
          "charge_userid":vm.dutyId,   //责任人id
          "check_userid":vm.examinerId,   //检查人id
          "valid": vm.radio,   //状态
          "target_objectid":vm.maintenanceValue.split("-")[0],   //对象id
          "plan_peroid":vm.cycleValue   //计划周期
        }
        window.localStorage.setItem("firstStepData",JSON.stringify(firstStepData));//缓存制定维保计划第一步数据(缺执行项)
        console.log("制定维保计划第一步数据",firstStepData);   
        this.$router.push({
          path:'/wbjhglzx',
          query: {type: 'add', id: vm.modelOptions[vm.modelValue].id , planname:vm.planName}
        })
      },
      onGetModelManageList(){//获取维保计划模板列表
        let vm=this;
        const params = {
          typeid:"",
          keyword:"",
          page_num: 1,
          page_size: 10000
        }; 
        getModelManageList(params)
        .then(response => {
          let res = response.data;
          vm.modelOptions = res.rows;
          window.localStorage.back_modelOptions=JSON.stringify(res.rows);//缓存维保计划模板-----
          console.log("计划模板列表",vm.modelOptions)
        }).catch(error => {
          
        })
      },
      changeModel(){//改变模板列表选项
        let vm=this;
        vm.maintenanceOptions=[];
        vm.maintenanceValue="";
        vm.cycleValue="";
        //console.log(vm.modelOptions[vm.modelValue].id)
        window.localStorage.back_modelValue=vm.modelValue;//缓存选中的维保计划模板下标-----
        vm.note=vm.modelOptions[vm.modelValue].note;//获取模板备注
        const params={
          "template_id":vm.modelOptions[vm.modelValue].id,
          "type_id":vm.modelOptions[vm.modelValue].targetid,
          "area_id":vm.areaIds
        }
        getObjList(params).then(response => {
          let res=response.data;
          vm.maintenanceOptions=res.rows;
          vm.lastTimeValue=res.rows.lasttime;
          window.localStorage.back_maintenanceOptions=JSON.stringify(res.rows);//缓存计划对象列表-----
          console.log("拉取对象成功",res.rows)
        }).catch(error => {
          console.log("拉取对象失败",error);
        })
        //计算周期
        let modelCycle=vm.modelOptions[vm.modelValue].cycle;
        //console.log("选择的周期是：",modelCycle)
        let date=new Date().getFullYear();
        if(modelCycle==365){//年度
          vm.cycleOptions=[{value: date+"年", label: date+"年"},{value: date+1+"年",label: date+1+"年"}];
          window.localStorage.back_cycleOptions=JSON.stringify(vm.cycleOptions);//缓存周期列表-----
        }else if(modelCycle==182){//半年度
          vm.cycleOptions=[{value: date+"年", label: date+"年"},{value: date+1+"年",label: date+1+"年"}];
          window.localStorage.back_cycleOptions=JSON.stringify(vm.cycleOptions);//缓存周期列表-----
        }else if(modelCycle==90){//季度
          vm.cycleOptions=[{value: date+"年1季度", label: date+"年1季度"},
                            {value: date+"年2季度", label: date+"年2季度"},
                            {value: date+"年3季度", label: date+"年3季度"},
                            {value: date+"年4季度", label: date+"年4季度"}];
          window.localStorage.back_cycleOptions=JSON.stringify(vm.cycleOptions);//缓存周期列表-----
        }else if(modelCycle==30){//月度
          vm.cycleOptions=[{value: date+"年1月", label: date+"年1月"},
                            {value: date+"年2月", label: date+"年2月"},
                            {value: date+"年3月", label: date+"年3月"},
                            {value: date+"年4月", label: date+"年4月"},
                            {value: date+"年5月", label: date+"年5月"},
                            {value: date+"年6月", label: date+"年6月"},
                            {value: date+"年7月", label: date+"年7月"},
                            {value: date+"年8月", label: date+"年8月"},
                            {value: date+"年9月", label: date+"年9月"},
                            {value: date+"年10月", label: date+"年10月"},
                            {value: date+"年11月", label: date+"年11月"},
                            {value: date+"年12月", label: date+"年12月"}];
          window.localStorage.back_cycleOptions=JSON.stringify(vm.cycleOptions);//缓存周期列表-----
        }else{//日常
          vm.cycleOptions=[{value: date+"年1月", label: date+"年1月"},
                            {value: date+"年2月", label: date+"年2月"},
                            {value: date+"年3月", label: date+"年3月"},
                            {value: date+"年4月", label: date+"年4月"},
                            {value: date+"年5月", label: date+"年5月"},
                            {value: date+"年6月", label: date+"年6月"},
                            {value: date+"年7月", label: date+"年7月"},
                            {value: date+"年8月", label: date+"年8月"},
                            {value: date+"年9月", label: date+"年9月"},
                            {value: date+"年10月", label: date+"年10月"},
                            {value: date+"年11月", label: date+"年11月"},
                            {value: date+"年12月", label: date+"年12月"}];
          window.localStorage.back_cycleOptions=JSON.stringify(vm.cycleOptions);//缓存周期列表-----
        }
      },
      getLastTime(){
        //console.log(this.maintenanceValue)
        this.lastTimeValue=this.maintenanceOptions[this.maintenanceValue.split("-")[1]].lasttime;
        window.localStorage.back_maintenanceValue=this.maintenanceValue;//缓存计划对象-----
        window.localStorage.back_lastTimeValue=this.lastTimeValue;//缓存上次任务结束时间-----
      },
      onPersonInCharge(){
        this.fetchStaff();
        this.newPersonnelDialogVisible=true;
      },
      fetchStaff() {//获取人员列表
        let vm = this;
        if(vm.areaIds==''||vm.areaIds==null){
          return;
        }
        vm.dutyDlgListLoading = true;
        let params = {
          kw:vm.kw_Personnel,
          is_fuzzy:true,
          page_num: 1,
          page_size: 10000,
          ril: 'S',
          area_id:vm.areaIds,
        };
        getStaffList(params)
        .then(response => {
          vm.dutyDlgList = response.data.rows;
          //console.log(vm.dutyDlgList)
          vm.kw_Personnel="";
          vm.dutyDlgListLoading = false;
        })
        .catch(error => {

          vm.dutyDlgListLoading = false;
        })
      },
      onChange(a,b,c){
        let vm=this;
        if(b){
          vm.$refs.dutyDlg.setCheckedKeys([]);
          vm.$refs.dutyDlg.setCheckedKeys([a.staff_id]);
        }else{
          vm.$refs.dutyDlg.setCheckedKeys([]);
        }
      },
      onChangeexaminerDlg(a,b,c){
        let vm=this;
        if(b){
          vm.$refs.examinerDlg.setCheckedKeys([]);
          vm.$refs.examinerDlg.setCheckedKeys([a.staff_id]);
        }else{
          vm.$refs.examinerDlg.setCheckedKeys([]);
        }
      },
      renderContent:function(createElement, { node, data, store }) {
        var vm = this;
        return createElement(
          'div', 
          {
            attrs:{
              style:"width:100%",
              title:`联系方式：${node.data.phone}`
            }
          },
          [
            createElement('span', node.label),
            createElement('span', 
              {attrs:{
                style:"float: right; margin-right: 20px"
              }},
              `${node.data.dept_name}`
            )
          ]
        );
      },
      onSearch(){
        this.fetchStaff();
      },
      onSearchExaminer(){
        this.onGetExaminer();
      },
      handleDutyDlgClick() {
        this.newPersonnelDialogVisible = false;
        var duty = this.$refs.dutyDlg.getCheckedNodes();
        if (duty.length > 0) {
          this.dutyName = duty[0].user_name;
          this.dutyId = duty[0].staff_id;
          window.localStorage.back_dutyName=this.dutyName;//缓存责任人名字
          window.localStorage.back_dutyId=this.dutyId;//缓存责任人id
        }
      },
      onExaminer(){
        this.onGetExaminer();
        this.newExaminerDialogVisible=true;
      },
      onGetExaminer() {//获取人员列表
        let vm = this;
        if(vm.areaIds==''||vm.areaIds==null){
          return;
        }
        this.dutyDlgListLoading = true;
        //vm.kw="";
        let params = {
          kw:vm.kw,
          is_fuzzy:true,
          page_num: 1,
          page_size: 10000,
          ril: 'S',
          area_id:vm.areaIds,
        };
        getStaffList(params)
        .then(response => {
          vm.examinerDlgList = response.data.rows;
          console.log(vm.examinerDlgList)
          vm.kw="";
          vm.dutyDlgListLoading = false;
        })
        .catch(error => {
          vm.dutyDlgListLoading = false;
        })
      },
      onExaminerSub(){
        this.newExaminerDialogVisible = false;
        var duty = this.$refs.examinerDlg.getCheckedNodes();
        if (duty.length > 0) {
          this.examinerName = duty[0].user_name;
          this.examinerId = duty[0].staff_id;
          window.localStorage.back_examinerName=this.examinerName;//缓存责任人名字
          window.localStorage.back_examinerId=this.examinerId;//缓存责任人id
        }
      }
      
    }
    
  }   


</script>



